<template>
  <div class="register">
    <el-dialog :visible="isShow" :show-close="false" width="600px">
      <div slot="title" class="title">用户注册</div>
      <!-- 注册面板内容部分 -->
      <div class="content">
        <!-- 使用el-form制作 -->
        <!-- 设置表单控件验证 -->
        <el-form :model="form" ref="form" label-width="70px" :rules="rules" class="form">
          <el-form-item prop="avatar" label="头像">
            <el-upload
              class="avatar-uploader"
              :action="baseURL+'/uploads'"
              name="image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item prop="username" label="昵称">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="手机">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item prop="pcode" label="图形码">
            <el-row>
              <el-col :span="16">
                <el-input v-model="form.pcode"></el-input>
              </el-col>
              <el-col :span="7" :offset="1">
                <img class="register-codeimg" :src="codeimg" @click="updateImg" alt />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item prop="rcode" label="图形码">
            <el-row>
              <el-col :span="16">
                <el-input v-model="form.rcode"></el-input>
              </el-col>
              <el-col :span="7" :offset="1">
                <el-button @click="getRcode">获取验证码</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="footer">
        <el-button @click="isShow=false">取消</el-button>
        <el-button type="primary" @click="confrimVerify">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getRcodes, registerUser } from "@/api/login.js";
export default {
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    }
  },
  data() {
    return {
      isShow: false,
      imageUrl: "",
      codeimg: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      baseURL: process.env.VUE_APP_URL,
      form: {
        avatar: "", //是	string	头像地址
        username: "", //是	string	用户名
        email: "", //是	string	邮箱
        phone: "", //是	string	手机号
        password: "", //是	string	密码
        pcode: "", // 图形码
        rcode: "" //是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: "请选择头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "change" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _email = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_email.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱"));
              }
            },
            trigger: "change"
          }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _phone = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_phone.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位密码", trigger: "change" }
        ],
        pcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          { min: 4, max: 4, message: "请输入 4 位验证码", trigger: "change" }
        ],
        rcode: [
          { required: true, message: "请输入短信验证码", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    // 点击按钮获得短信验证码
    getRcode() {
      // 开关思想
      let flag = true;
      // 使用el-form的validateField,进行局部验证
      this.$refs.form.validateField(["phone", "pcode"], err => {
        if (err != "") {
          flag = false;
        }
      });
      if (flag) {
        getRcodes({ code: this.form.pcode, phone: this.form.phone }).then(
          res => {
            this.$message.success(res.data.captcha + "");
          }
        );
      }
    },

    // 设置整个表单验证
    confrimVerify() {
      this.$refs.form.validate(result => {
        if (result) {
          // this.$message.success("验证成功");
          registerUser(this.form).then(() => {
            // window.console.log(res);
            // 成功了关闭注册面板
            this.$message.success("注册成功!");
            this.isShow = false;
          });
        }
      });
    },

    // 上传头像成功的处理
    handleAvatarSuccess(res) {
      // 上传成功后，我们要做一次验证
      this.form.avatar = res.data.file_path;
      this.imageUrl = this.baseURL + "/" + res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    // 上传前， 设置图片限制
    beforeAvatarUpload(file) {
      let typeIsPass = file.type === "image/jpeg" || file.type === "image/png";
      let isLt2M = file.size / 1024 / 1024 < 2;
      if (!typeIsPass) {
        this.$message.error("上传头像图片只能是 JPC,PNG 格式");
      }
      if (!isLt2M) {
        this.$message.error("上传头像大小不能大于2M");
      }

      return typeIsPass && isLt2M;
    },

    // 点击图片 更新图片
    updateImg() {
      this.codeimg =
        this.baseURL + "/captcha?type=sendsms&d=" + new Date().getTime();
    }
  }
};
</script>
<style lang="less" >
.register {
  .el-dialog__header {
    padding: 0;
  }
  .title {
    height: 60px;
    background: linear-gradient(to right, #01c5fa, #1394fa);
    text-align: center;
    line-height: 60px;
    color: #fff;
  }
  .footer {
    text-align: center;
  }
  .form {
    .avatar-uploader {
      text-align: center;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #ccc;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .register-codeimg {
      width: 100%;
      height: 40px;
    }
  }
}
</style>
